<template>
  <div class="search-wrap">
    <div>
      <el-input
        ref="nameInput"
        v-model="name"
        placeholder="请输入名称"
        @keydown.native="handleKeyDdownName"
        @input="handleInputName"
      />
    </div>
    <div v-if="showSearchCode">
      <el-input
        ref="codeInput"
        v-model="code"
        placeholder="请输入编码"
        @keydown.native="handleKeyDdownCode"
        @input="handleInputCode"
      />
    </div>
    <el-button
      icon="el-icon-search"
      class="search-button"
      @click="handleSearchData"
    >查询</el-button>
  </div>
</template>
<script>
export default {
  props: {
    showSearchCode: { // 是否展示编码搜索框，默认不展示
      type: Boolean,
      default: false
    },
    searchName: {
      type: String,
      default: ''
    },
    searchCode: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      name: this.searchName,
      code: this.searchCode
    }
  },
  methods: {
    // 名称输入框键盘事件
    handleKeyDdownName (event) {
      if (event.keyCode === 13) {
        this.handleSearchData()
      }
      if ([37, 39].includes(event.keyCode)) {
        event.preventDefault(); // 阻止默认行为
        this.$refs?.codeInput && this.$refs.codeInput.focus();
      }
    },
    // 编码输入框键盘事件
    handleKeyDdownCode (event) {
      if (event.keyCode === 13) {
        this.handleSearchData()
      }
      if ([37, 39].includes(event.keyCode)) {
        event.preventDefault(); // 阻止默认行为
        this.$refs?.nameInput && this.$refs.nameInput.focus();
      }
    },
    // 查询
    handleSearchData () {
      this.$emit('searchData')
    },
    // 输入名称
    handleInputName () {
      this.$emit('update:searchName', this.name)
    },
    // 输入编码
    handleInputCode () {
      this.$emit('update:searchCode', this.code)
    },
    // 清空搜索状态
    clearSearchState () {
      this.name = ''
      this.code = ''
      this.$emit('update:searchName', this.name)
      this.$emit('update:searchCode', this.code)
    },
  }
}
</script>
<style lang="less" scoped>
.search-wrap {
  display: flex;
  background-color: #f9f9f9;
  padding: 10px 20px;
  border-bottom: 1px solid #e6e6e6;
  border-radius: 10px 10px 0 0;
  /deep/ .el-input:nth-child(2) {
    margin-top: 10px;
  }
  div {
    width: 100%;
    margin-right: 10px;
  }
}
.search-button {
  background-color: #5a9cf8 !important;
  color: #fff !important;
  &:hover {
    background-color: #78aff9 !important;
  }
}
</style>
